package io.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程支持 -- HTTP 返回
 */
public class BioServer2 {
    static ExecutorService executorService = Executors.newCachedThreadPool();
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器已启动，监听8080端口");
        while(true) {
            final Socket request = serverSocket.accept();
            executorService.execute(() -> {
                System.out.println("建立连接，" + request.toString());
                BufferedReader bufferedReader = null;
//                BufferedWriter writer = null;
                OutputStream outputStream = null;
                try {
                    bufferedReader = new BufferedReader(new InputStreamReader(request.getInputStream()));
//                    writer = new BufferedWriter(new OutputStreamWriter(request.getOutputStream()));
                    outputStream = request.getOutputStream();
                    String str;
                    while ((str = bufferedReader.readLine()) != null && str.length() != 0)
                        System.out.println("收到数据：" + str);
//                    writer.write("HTTP/1.1 200 OK\n");
//                    writer.write("Content-Length: 12\n");
//                    writer.write("\nHello World!\n");
//                    writer.flush();
                    outputStream.write("HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!\r\n".getBytes());
                    outputStream.flush();
                    System.out.println("数据发送完毕");
                    System.out.println("数据接收完毕，数据来自：" + request.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if(bufferedReader != null)
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    if(outputStream != null) {
                        try {
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
//                    if(writer != null) {
//                        try {
//                            writer.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
                }
            });

        }
    }
}
